﻿using System;
using System.Collections.Generic;
using System.Web;
using EPiServer.Personalization.VisitorGroups;
using Facebook;
using Facebook.Web;

namespace SocialPack.VisitorGroups.Facebook.Gender
{
    [VisitorGroupCriterion(
        Category = "Facebook",
        DisplayName = "Gender",
        Description = "Criterion that matches gender in Facebook integration",
        LanguagePath = "/shell/cms/visitorgroups/criteria/gender")]
    public class GenderCriteria : CriterionBase<GenderModel>
    {
        private static readonly log4net.ILog _log =
            log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

        public override bool IsMatch(System.Security.Principal.IPrincipal principal,
                                     HttpContextBase httpContext)
        {
            try
            {
                FacebookWebContext context = new FacebookWebContext();

                if (context.AccessToken == null) // user has not allowed us to know the gender
                    return false;

                var client = new FacebookClient(context.AccessToken);
                var me = (IDictionary<string, object>) client.Get("me");

                string gender = me["gender"].ToString();

                return Model.Gender.ToString().ToLower().Equals(gender.ToLower());
            }
            catch (Exception ex)
            {
                _log.Error("GenderCriteria IsMatch failed", ex);
                return false;
            }
        }
    }
}